﻿using System.IO;
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Administration;
using System.Net.Mail;
using System.Net;
using System.Text.RegularExpressions;
using Microsoft.SharePoint.Utilities;

namespace RealDolmen.SharePoint.ListFeatures.EmailThisFile
{
    public class SendEmail : UnsecuredLayoutsPageBase
    {
        #region " - Controls - "
        protected TextBox txtSubject, txtBody, txtRecipient, txtSender;
        protected Literal litFileName, litError, litRecipient, litSender;
        #endregion // Controls

        #region " - Variables - "
        protected SPListItem currentListItem = null;
        protected string sourceUrl = string.Empty;
        private string defaultSubject = string.Empty;
        private string defaultBody = string.Empty;
        private ListFeature listFeature;
        #endregion // Variables

        #region " - Properties - "
        public string DefaultSubject
        {
            get { return defaultSubject; }
            set { defaultSubject = value; }
        }

        public string DefaultBody
        {
            get { return defaultBody; }
            set { defaultBody = value; }
        }

        protected ListFeature ListFeature
        {
            get { return listFeature; }
            set { listFeature = value; }
        }
        #endregion // Properties
        
        #region " - Events - "
        protected override void OnInit(System.EventArgs e)
        {
            ListFeature = ListFeature.Current;
            if (ListFeature != null)
            {
                ListFeature.Register(this);
            }
            ((DialogMaster)this.Page.Master).OkButton.Text = "Send";
            ((DialogMaster)this.Page.Master).OkButton.Click += new EventHandler(Send);
        }

        protected override void OnLoad(EventArgs e)
        {
            SPList oList = SPContext.Current.List;
            currentListItem = SPContext.Current.ListItem;
            sourceUrl = SPUtility.GetFullUrl(SPContext.Current.Site, oList.RootFolder.Url);

            if (!IsPostBack)
            {
                try
                {
                    litFileName.Text = currentListItem.Name;
                    txtSubject.Text = String.Format(DefaultSubject, currentListItem.Name);
                    txtBody.Text = String.Format(DefaultBody, currentListItem.Name);
                    txtSender.Text = SPContext.Current.Web.CurrentUser.Email;
                    if (string.IsNullOrEmpty(txtSender.Text))
                        litSender.Text = "Your e-mail address is not filled in your user profile";
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.TraceError("OnLoad error: " + ex.ToString());
                    litError.Text = "An error occurred while loading this page. <br />A new log entry has been added.<br />Please contact your system administrator";
                }
            }
        }

        protected void Send(object sender, EventArgs e)
        {
            if (!CheckValidation())
                return;
            Stream fileStream = null;
            bool error = false;
            try
            {
                SPWebApplication webApp = SPContext.Current.Site.WebApplication;
                string smtpServer = webApp.OutboundMailServiceInstance.Server.Address;

                // create mail message object
                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(
                    txtSender.Text,
                    txtRecipient.Text,
                    txtSubject.Text,
                    txtBody.Text);

                fileStream = currentListItem.File.OpenBinaryStream(SPOpenBinaryOptions.None);
                mail.Attachments.Add(new Attachment(fileStream, currentListItem.Name));

                SmtpClient sc = new SmtpClient(smtpServer);
                sc.Credentials = CredentialCache.DefaultNetworkCredentials;
                sc.Send(mail);

            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError("Send() error: " + ex.ToString());
                litError.Text = "An error occurred while loading submitting this form. <br />A new log entry has been added.<br />Please contact your system administrator";
                error = true;
            }
            finally
            {
                if (fileStream != null)
                    fileStream.Dispose();
            }
            if (!error)
                Page.ClientScript.RegisterStartupScript(this.GetType(), "OkAndClose", "<script>window.returnValue=true;doCancel();</script>");
        }
        #endregion // Events

        #region " - Methods - "
        private bool CheckValidation()
        {
            if (string.IsNullOrEmpty(txtRecipient.Text))
            {
                litError.Text = "Please correct the errors in the form";
                litRecipient.Text = "Please enter a recipient";
                return false;
            }
            Regex regEx = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
            if (!regEx.IsMatch(txtRecipient.Text))
            {
                litError.Text = "Please correct the errors in the form";
                litRecipient.Text = "Please enter a valid e-mail address";
                return false;
            }

            if (string.IsNullOrEmpty(txtSender.Text))
            {
                litError.Text = "Please correct the errors in the form";
                return false;
            }

            litError.Text = string.Empty;
            litRecipient.Text = string.Empty;
            return true;
        }
        #endregion // Methods
    }
}